import React, { useState } from 'react'
import { Card, List, Badge, Button, Space, Tag, Modal, Form, Input, Select, message, Avatar, Tabs } from 'antd'
import { BellOutlined, DeleteOutlined, EyeOutlined, SettingOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import Layout from '../components/Layout/Layout'
import dayjs from 'dayjs'

const { TextArea } = Input
const { Option } = Select
const { TabPane } = Tabs

export default function Notifications() {
  const [notifications, setNotifications] = useState([
    {
      id: 1,
      title: 'A区空调系统故障',
      content: 'A区2楼空调系统出现故障，温度异常，请及时处理',
      type: 'error',
      category: 'device',
      isRead: false,
      createdAt: '2024-01-15 14:30:00',
      sender: '设备监控系统'
    },
    {
      id: 2,
      title: '停车位不足预警',
      content: 'B区停车位使用率已达95%，建议引导车辆到其他区域',
      type: 'warning',
      category: 'parking',
      isRead: false,
      createdAt: '2024-01-15 13:45:00',
      sender: '停车管理系统'
    },
    {
      id: 3,
      title: '能耗异常提醒',
      content: '今日能耗较昨日同期增长25%，请检查设备运行状态',
      type: 'info',
      category: 'energy',
      isRead: true,
      createdAt: '2024-01-15 09:15:00',
      sender: '能耗监控系统'
    },
    {
      id: 4,
      title: '访客预约审批',
      content: '科技有限公司张先生申请明日访问，请及时审批',
      type: 'info',
      category: 'visitor',
      isRead: true,
      createdAt: '2024-01-14 16:20:00',
      sender: '访客管理系统'
    }
  ])

  const [settings, setSettings] = useState({
    device: { email: true, sms: false, push: true },
    parking: { email: true, sms: true, push: true },
    energy: { email: false, sms: false, push: true },
    visitor: { email: true, sms: false, push: true },
    security: { email: true, sms: true, push: true }
  })

  const [activeTab, setActiveTab] = useState('all')
  const [settingsVisible, setSettingsVisible] = useState(false)
  const [composeVisible, setComposeVisible] = useState(false)
  const [form] = Form.useForm()

  const typeColors = {
    error: 'red',
    warning: 'orange',
    info: 'blue',
    success: 'green'
  }

  const typeIcons = {
    error: '🚨',
    warning: '⚠️',
    info: 'ℹ️',
    success: '✅'
  }

  const categoryNames = {
    device: '设备',
    parking: '停车',
    energy: '能耗',
    visitor: '访客',
    security: '安全'
  }

  const filteredNotifications = notifications.filter(notification => {
    if (activeTab === 'all') return true
    if (activeTab === 'unread') return !notification.isRead
    return notification.category === activeTab
  })

  const unreadCount = notifications.filter(n => !n.isRead).length

  const handleMarkAsRead = (id) => {
    setNotifications(prev =>
      prev.map(item =>
        item.id === id ? { ...item, isRead: true } : item
      )
    )
  }

  const handleMarkAllAsRead = () => {
    setNotifications(prev =>
      prev.map(item => ({ ...item, isRead: true }))
    )
    message.success('已标记所有通知为已读')
  }

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确认删除这条通知吗？',
      onOk: () => {
        setNotifications(prev => prev.filter(item => item.id !== id))
        message.success('删除成功')
      }
    })
  }

  const handleDeleteAll = () => {
    Modal.confirm({
      title: '确认删除',
      content: '确认删除所有通知吗？',
      onOk: () => {
        setNotifications([])
        message.success('删除成功')
      }
    })
  }

  const handleSendNotification = async (values) => {
    try {
      const newNotification = {
        id: Date.now(),
        ...values,
        isRead: false,
        createdAt: new Date().toLocaleString(),
        sender: '管理员'
      }
      setNotifications(prev => [newNotification, ...prev])
      message.success('通知发送成功')
      setComposeVisible(false)
      form.resetFields()
    } catch (error) {
      message.error('发送失败')
    }
  }

  const handleUpdateSettings = (category, type, value) => {
    setSettings(prev => ({
      ...prev,
      [category]: {
        ...prev[category],
        [type]: value
      }
    }))
    message.success('设置已更新')
  }

  return (
    <Layout>
      <div style={{ padding: '24px' }}>
        <Card 
          title={
            <Space>
              <BellOutlined />
              通知中心
              {unreadCount > 0 && (
                <Badge count={unreadCount} style={{ marginLeft: 8 }} />
              )}
            </Space>
          }
          extra={
            <Space>
              <Button onClick={() => setComposeVisible(true)}>
                发送通知
              </Button>
              <Button onClick={handleMarkAllAsRead} disabled={unreadCount === 0}>
                全部已读
              </Button>
              <Button onClick={handleDeleteAll} danger>
                清空通知
              </Button>
              <Button 
                icon={<SettingOutlined />}
                onClick={() => setSettingsVisible(true)}
              >
                设置
              </Button>
            </Space>
          }
        >
          <Tabs activeKey={activeTab} onChange={setActiveTab}>
            <TabPane tab={`全部 (${notifications.length})`} key="all" />
            <TabPane tab={`未读 (${unreadCount})`} key="unread" />
            <TabPane tab="设备" key="device" />
            <TabPane tab="停车" key="parking" />
            <TabPane tab="能耗" key="energy" />
            <TabPane tab="访客" key="visitor" />
            <TabPane tab="安全" key="security" />
          </Tabs>

          <List
            itemLayout="horizontal"
            dataSource={filteredNotifications}
            renderItem={(item) => (
              <List.Item
                style={{
                  backgroundColor: item.isRead ? 'transparent' : '#f6ffed',
                  padding: '16px',
                  borderRadius: '6px',
                  marginBottom: '8px'
                }}
                actions={[
                  !item.isRead && (
                    <Button 
                      type="link" 
                      size="small"
                      onClick={() => handleMarkAsRead(item.id)}
                    >
                      标记已读
                    </Button>
                  ),
                  <Button 
                    type="link" 
                    size="small" 
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => handleDelete(item.id)}
                  >
                    删除
                  </Button>
                ]}
              >
                <List.Item.Meta
                  avatar={
                    <Avatar 
                      style={{ 
                        backgroundColor: typeColors[item.type],
                        fontSize: '18px'
                      }}
                    >
                      {typeIcons[item.type]}
                    </Avatar>
                  }
                  title={
                    <Space>
                      <span style={{ fontWeight: item.isRead ? 'normal' : 'bold' }}>
                        {item.title}
                      </span>
                      <Tag color={typeColors[item.type]} size="small">
                        {categoryNames[item.category]}
                      </Tag>
                      {!item.isRead && <Badge status="processing" />}
                    </Space>
                  }
                  description={
                    <div>
                      <div style={{ marginBottom: 8 }}>{item.content}</div>
                      <div style={{ fontSize: 12, color: '#999' }}>
                        {item.sender} • {dayjs(item.createdAt).format('MM-DD HH:mm')}
                      </div>
                    </div>
                  }
                />
              </List.Item>
            )}
          />
        </Card>

        {/* 发送通知模态框 */}
        <Modal
          title="发送通知"
          open={composeVisible}
          onOk={() => form.submit()}
          onCancel={() => setComposeVisible(false)}
          width={600}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSendNotification}
          >
            <Form.Item name="title" label="通知标题" rules={[{ required: true }]}>
              <Input placeholder="请输入通知标题" />
            </Form.Item>
            <Form.Item name="content" label="通知内容" rules={[{ required: true }]}>
              <TextArea rows={4} placeholder="请输入通知内容" />
            </Form.Item>
            <Form.Item name="type" label="通知类型" rules={[{ required: true }]}>
              <Select placeholder="请选择通知类型">
                <Option value="info">信息</Option>
                <Option value="warning">警告</Option>
                <Option value="error">错误</Option>
                <Option value="success">成功</Option>
              </Select>
            </Form.Item>
            <Form.Item name="category" label="通知分类" rules={[{ required: true }]}>
              <Select placeholder="请选择通知分类">
                <Option value="device">设备</Option>
                <Option value="parking">停车</Option>
                <Option value="energy">能耗</Option>
                <Option value="visitor">访客</Option>
                <Option value="security">安全</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>

        {/* 通知设置模态框 */}
        <Modal
          title="通知设置"
          open={settingsVisible}
          onCancel={() => setSettingsVisible(false)}
          footer={[
            <Button key="close" onClick={() => setSettingsVisible(false)}>
              关闭
            </Button>
          ]}
          width={600}
        >
          <div>
            {Object.entries(settings).map(([category, config]) => (
              <Card key={category} title={categoryNames[category]} size="small" style={{ marginBottom: 16 }}>
                <Space direction="vertical" style={{ width: '100%' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span>邮件通知</span>
                    <Button
                      type={config.email ? 'primary' : 'default'}
                      size="small"
                      onClick={() => handleUpdateSettings(category, 'email', !config.email)}
                    >
                      {config.email ? '已开启' : '已关闭'}
                    </Button>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span>短信通知</span>
                    <Button
                      type={config.sms ? 'primary' : 'default'}
                      size="small"
                      onClick={() => handleUpdateSettings(category, 'sms', !config.sms)}
                    >
                      {config.sms ? '已开启' : '已关闭'}
                    </Button>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span>推送通知</span>
                    <Button
                      type={config.push ? 'primary' : 'default'}
                      size="small"
                      onClick={() => handleUpdateSettings(category, 'push', !config.push)}
                    >
                      {config.push ? '已开启' : '已关闭'}
                    </Button>
                  </div>
                </Space>
              </Card>
            ))}
          </div>
        </Modal>
      </div>
    </Layout>
  )
}
